<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
  <meta name="theme-color" content="#222">
  <meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

  <link rel="stylesheet" href="/css/main.css">



  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

  <script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {
      "hostname": "holidaypenguin.gitee.io",
      "root": "/",
      "images": "/images",
      "scheme": "Mist",
      "version": "8.2.2",
      "exturl": false,
      "sidebar": {
        "position": "right",
        "display": "always",
        "padding": 18,
        "offset": 12
      },
      "copycode": true,
      "bookmark": {
        "enable": false,
        "color": "#222",
        "save": "auto"
      },
      "fancybox": false,
      "mediumzoom": false,
      "lazyload": false,
      "pangu": false,
      "comments": {
        "style": "tabs",
        "active": null,
        "storage": true,
        "lazyload": false,
        "nav": null
      },
      "motion": {
        "enable": true,
        "async": true,
        "transition": {
          "post_block": "fadeIn",
          "post_header": "fadeInDown",
          "post_body": "fadeInDown",
          "coll_header": "fadeInLeft",
          "sidebar": "slideUpIn"
        }
      },
      "prism": false,
      "i18n": {
        "placeholder": "搜索...",
        "empty": "没有找到任何搜索结果：${query}",
        "hits_time": "找到 ${hits} 个搜索结果（用时 ${time} 毫秒）",
        "hits": "找到 ${hits} 个搜索结果"
      },
      "path": "/search.xml",
      "localsearch": {
        "enable": true,
        "trigger": "auto",
        "top_n_per_article": 1,
        "unescape": false,
        "preload": false
      }
    };
  </script>
  <meta property="og:type" content="article">
  <meta property="og:title" content="JavsScript ES11&amp;ES2020的新特性">
  <meta property="og:url" content="https://holidaypenguin.gitee.io/blob/2021-06-07-new-features-of-javsscript-es11-&-es2020/index.html">
  <meta property="og:site_name" content="HolidayPenguin">
  <meta property="og:locale" content="zh_CN">
  <meta property="og:image" content="https://visitor-badge.glitch.me/badge?page_id=holidaypenguin.gitee.io/">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/es/0002.png">
  <meta property="article:published_time" content="2021-06-07T08:42:53.000Z">
  <meta property="article:modified_time" content="2021-06-07T08:42:53.000Z">
  <meta property="article:author" content="holidaypenguin">
  <meta property="article:tag" content="JavaScript">
  <meta property="article:tag" content="Ecma">
  <meta property="article:tag" content="ECMAScript">
  <meta property="article:tag" content="ES11">
  <meta property="article:tag" content="ES2020">
  <meta property="article:tag" content="ECMAScript 2020">
  <meta name="twitter:card" content="summary">
  <meta name="twitter:image" content="https://visitor-badge.glitch.me/badge?page_id=holidaypenguin.gitee.io/">


  <link rel="canonical" href="https://holidaypenguin.gitee.io/blob/2021-06-07-new-features-of-javsscript-es11-&-es2020/">


  <script class="page-configurations">
    // https://hexo.io/docs/variables.html
    CONFIG.page = {
      sidebar: "",
      isHome: false,
      isPost: true,
      lang: 'zh-CN'
    };
  </script>
  <title>JavsScript ES11&ES2020的新特性 | HolidayPenguin</title>





  <noscript>
    <style>
      body {
        margin-top: 2rem;
      }

      .use-motion .menu-item,
      .use-motion .sidebar,
      .use-motion .post-block,
      .use-motion .pagination,
      .use-motion .comments,
      .use-motion .post-header,
      .use-motion .post-body,
      .use-motion .collection-header {
        visibility: visible;
      }

      .use-motion .header,
      .use-motion .site-brand-container .toggle,
      .use-motion .footer {
        opacity: initial;
      }

      .use-motion .site-title,
      .use-motion .site-subtitle,
      .use-motion .custom-logo-image {
        opacity: initial;
        top: initial;
      }

      .use-motion .logo-line {
        transform: scaleX(1);
      }

      .search-pop-overlay,
      .sidebar-nav {
        display: none;
      }

      .sidebar-panel {
        display: block;
      }
    </style>
  </noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">
        <div class="site-brand-container">
          <div class="site-nav-toggle">
            <div class="toggle" aria-label="切换导航栏" role="button">
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
            </div>
          </div>

          <div class="site-meta">

            <a href="/" class="brand" rel="start">
              <i class="logo-line"></i>
              <h1 class="site-title">HolidayPenguin</h1>
              <i class="logo-line"></i>
            </a>
          </div>

          <div class="site-nav-right">
            <div class="toggle popup-trigger">
              <i class="fa fa-search fa-fw fa-lg"></i>
            </div>
          </div>
        </div>



        <nav class="site-nav">
          <ul class="main-menu menu">
            <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
            <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
            <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
            <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
            <li class="menu-item menu-item-search">
              <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
              </a>
            </li>
          </ul>
        </nav>



        <div class="search-pop-overlay">
          <div class="popup search-popup">
            <div class="search-header">
              <span class="search-icon">
                <i class="fa fa-search"></i>
              </span>
              <div class="search-input-container">
                <input autocomplete="off" autocapitalize="off" maxlength="80" placeholder="搜索..." spellcheck="false" type="search" class="search-input">
              </div>
              <span class="popup-btn-close" role="button">
                <i class="fa fa-times-circle"></i>
              </span>
            </div>
            <div class="search-result-container no-result">
              <div class="search-result-icon">
                <i class="fa fa-spinner fa-pulse fa-5x"></i>
              </div>
            </div>

          </div>
        </div>

      </div>


      <div class="toggle sidebar-toggle" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
      </div>

      <aside class="sidebar">

        <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
          <ul class="sidebar-nav">
            <li class="sidebar-nav-toc">
              文章目录
            </li>
            <li class="sidebar-nav-overview">
              站点概览
            </li>
          </ul>

          <div class="sidebar-panel-container">
            <!--noindex-->
            <div class="post-toc-wrap sidebar-panel">
              <div class="post-toc animated">
                <ol class="nav">
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8C%B9%E9%85%8D%E5%A4%9A%E4%B8%AA%E5%AD%97%E7%AC%A6%E4%B8%B2-string-prototype-matchAll"><span class="nav-number">1.</span> <span class="nav-text">匹配多个字符串 string.prototype.matchAll()</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B7%BB%E5%8A%A0-g"><span class="nav-number">1.1.</span> <span class="nav-text">添加 &#x2F;g</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%8D%95%E8%8E%B7%E7%BB%84"><span class="nav-number">1.2.</span> <span class="nav-text">正则表达式捕获组</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%9C%80%E5%A5%BD%E4%BD%BF%E7%94%A8-matchAll"><span class="nav-number">1.3.</span> <span class="nav-text">最好使用 .matchAll()</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#matchAll-%E5%A6%82%E4%BD%95%E5%B7%A5%E4%BD%9C"><span class="nav-number">1.4.</span> <span class="nav-text">.matchAll()如何工作</span></a></li>
                    </ol>
                  </li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8A%A8%E6%80%81-import"><span class="nav-number">2.</span> <span class="nav-text">动态 import</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#BigInt-%E4%BB%BB%E6%84%8F%E7%B2%BE%E5%BA%A6%E6%95%B4%E6%95%B0"><span class="nav-number">3.</span> <span class="nav-text">BigInt - 任意精度整数</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#export-%E4%B8%8E-import-%E7%9A%84%E5%A4%8D%E5%90%88%E5%86%99%E6%B3%95%E8%A1%A5%E5%85%85"><span class="nav-number">4.</span> <span class="nav-text">export 与 import 的复合写法补充</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%BF%94%E5%9B%9E%E6%A8%A1%E5%9D%97%E7%9A%84%E5%85%83%E4%BF%A1%E6%81%AF-import-meta"><span class="nav-number">5.</span> <span class="nav-text">返回模块的元信息 import.meta</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%A7%84%E8%8C%83for-in%E5%BE%AA%E7%8E%AF%E7%9A%84%E6%9F%90%E4%BA%9B%E8%A1%8C%E4%B8%BA"><span class="nav-number">6.</span> <span class="nav-text">规范for-in循环的某些行为</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%A9%BA%E5%80%BC%E5%90%88%E5%B9%B6%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="nav-number">7.</span> <span class="nav-text">空值合并运算符 ??</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%AF%E9%80%89%E9%93%BE%E6%93%8D%E4%BD%9C%E7%AC%A6"><span class="nav-number">8.</span> <span class="nav-text">可选链操作符</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%8F%8F%E8%BF%B0"><span class="nav-number">8.1.</span> <span class="nav-text">描述</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%AF%E9%80%89%E9%93%BE%E4%B8%8E%E5%87%BD%E6%95%B0%E8%B0%83%E7%94%A8"><span class="nav-number">8.2.</span> <span class="nav-text">可选链与函数调用</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%AF%E9%80%89%E9%93%BE%E8%AE%BF%E9%97%AE%E6%95%B0%E7%BB%84%E5%85%83%E7%B4%A0"><span class="nav-number">8.3.</span> <span class="nav-text">可选链访问数组元素</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%89%B9%E6%80%A7"><span class="nav-number">8.4.</span> <span class="nav-text">特性</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#Babel%E6%8F%92%E4%BB%B6%E8%BD%AC%E6%8D%A2"><span class="nav-number">8.5.</span> <span class="nav-text">Babel插件转换</span></a></li>
                    </ol>
                  </li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#Promise-allSettled"><span class="nav-number">9.</span> <span class="nav-text">Promise.allSettled</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A0%87%E5%87%86%E5%8C%96%E7%9A%84-globalThis-%E5%AF%B9%E8%B1%A1"><span class="nav-number">10.</span> <span class="nav-text">标准化的 globalThis 对象</span></a></li>
                </ol>
                </li>
                <li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8F%82%E8%80%83"><span class="nav-number"></span> <span class="nav-text">参考</span></a>
              </div>
            </div>
            <!--/noindex-->

            <div class="site-overview-wrap sidebar-panel">
              <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
                <p class="site-author-name" itemprop="name">holidaypenguin</p>
                <div class="site-description" itemprop="description"></div>
              </div>
              <div class="site-state-wrap site-overview-item animated">
                <nav class="site-state">
                  <div class="site-state-item site-state-posts">
                    <a href="/archives/">

                      <span class="site-state-item-count">138</span>
                      <span class="site-state-item-name">日志</span>
                    </a>
                  </div>
                  <div class="site-state-item site-state-categories">
                    <a href="/categories/">

                      <span class="site-state-item-count">26</span>
                      <span class="site-state-item-name">分类</span></a>
                  </div>
                  <div class="site-state-item site-state-tags">
                    <a href="/tags/">

                      <span class="site-state-item-count">234</span>
                      <span class="site-state-item-name">标签</span></a>
                  </div>
                </nav>
              </div>
              <div class="links-of-author site-overview-item animated">
                <span class="links-of-author-item">
                  <a href="https://github.com/holidaypenguin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;holidaypenguin" rel="noopener" target="_blank"><i class="github fa-fw"></i>GitHub</a>
                </span>
                <span class="links-of-author-item">
                  <a href="mailto:songshipeng2016@gmail.com" title="E-Mail → mailto:songshipeng2016@gmail.com" rel="noopener" target="_blank"><i class="envelope fa-fw"></i>E-Mail</a>
                </span>
              </div>



            </div>
          </div>
        </div>
      </aside>
      <div class="sidebar-dimmer"></div>


    </header>


    <div class="back-to-top" role="button">
      <i class="fa fa-arrow-up"></i>
      <span>0%</span>
    </div>

    <noscript>
      <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
    </noscript>


    <div class="main-inner post posts-expand">





      <div class="post-block">



        <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
          <link itemprop="mainEntityOfPage" href="https://holidaypenguin.gitee.io/blob/2021-06-07-new-features-of-javsscript-es11-&-es2020/">

          <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
            <meta itemprop="image" content="/images/avatar.gif">
            <meta itemprop="name" content="holidaypenguin">
            <meta itemprop="description" content="">
          </span>

          <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
            <meta itemprop="name" content="HolidayPenguin">
          </span>
          <header class="post-header">
            <h1 class="post-title" itemprop="name headline">
              JavsScript ES11&ES2020的新特性
            </h1>

            <div class="post-meta-container">
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>

                  <time title="创建时间：2021-06-07 16:42:53" itemprop="dateCreated datePublished" datetime="2021-06-07T16:42:53+08:00">2021-06-07</time>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-folder"></i>
                  </span>
                  <span class="post-meta-item-text">分类于</span>
                  <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                    <a href="/categories/JavaScript/" itemprop="url" rel="index"><span itemprop="name">JavaScript</span></a>
                  </span>
                </span>


                <span id="/blob/2021-06-07-new-features-of-javsscript-es11-&-es2020/" class="post-meta-item leancloud_visitors" data-flag-title="JavsScript ES11&ES2020的新特性" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
              </div>

              <div class="post-description">
                <!-- more -->
              </div>
            </div>
          </header>




          <div class="post-body" itemprop="articleBody">
            <p><a target="_blank" rel="noopener" href="https://github.com/jwenjian/visitor-count-badge"><img src="" data-original="https://visitor-badge.glitch.me/badge?page_id=holidaypenguin.gitee.io/" alt="总访客数量"></a></p>
            <p>写在前面的话标准非实际情况。</p>
            <p>ECMAScript 2020，ECMA-262 标准版本的第11版（通常称为ES2020或ES11），于 2020 年 6 月完成。</p>
            <p>This specification, the 11th edition, introduces the <code>matchAll</code> method for Strings, to produce an iterator for all match objects generated by a global regular expression; <code>import()</code>, a syntax to asynchronously import Modules with a dynamic specifier; <code>BigInt</code>, a new number primitive for working with arbitrary precision integers; <code>Promise.allSettled</code>, a new Promise combinator that does not short-circuit; <code>globalThis</code>, a universal way to access the global <code>this</code> value; dedicated <code>export * as ns from &#39;module&#39;</code> syntax for use within modules; increased standardization of <code>for-in</code> enumeration order; <code>import.meta</code>, a host-populated object available in Modules that may contain contextual information about the Module; as well as adding two new syntax features to improve working with “nullish” values (<code>null</code> or <code>undefined</code>): nullish coalescing, a value selection operator; and <code>optional chaining</code>, a property access and function invocation operator that short-circuits if the value to access/invoke is nullish.</p>
            <ul>
              <li>匹配多个字符串 matchAll</li>
              <li>动态 import()</li>
              <li>任意精度整数 BigInt</li>
              <li>返回所有Promise结果 Promise.allSettled</li>
              <li>标准化的 globalThis 对象</li>
              <li>export 与 import 的复合写法补充</li>
              <li>规范for-in循环的某些行为</li>
              <li>返回模块的元信息 import.meta</li>
              <li>空值合并运算符 ??</li>
              <li>可选链操作符</li>
            </ul>
            <h2 id="匹配多个字符串-string-prototype-matchAll"><a href="#匹配多个字符串-string-prototype-matchAll" class="headerlink" title="匹配多个字符串 string.prototype.matchAll()"></a>匹配多个字符串 string.prototype.matchAll()</h2>
            <p>当你读到这个 <code>matchAll</code>时，它可能会在 <code>Chrome C73</code>中正式实现 - 如果没有，它仍然值得一看。特别是如果你是一个正则表达式瘾君子。</p>
            <p>如果你谷歌搜索”javascript string match all”，第一条结果可能会是这样的**How do I write a regular expression to “match all”?**。 排名靠前的结果会建议你使用 <code>String.match</code>匹配的时候在正则表达式或者 <code>RegExp.exc</code> 或者 <code>RegExp.text</code>后加上 <code>/g</code>…</p>
            <p>首先，我们来看下旧的规范是如何运行的。</p>
            <p><code>String.match</code>， <code>match</code>只返回字符串参数第一个符合匹配的。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">let</span> string = <span class="string">&#x27;Hello&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> matches = string.match(<span class="string">&#x27;l&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(matches[<span class="number">0</span>])</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>匹配的结果是单个 <code>&#39;l&#39;</code>。(注意： <code>match</code>匹配的结果存储在 <code>matches[0]</code>而非在 <code>matches</code>)，在字符串 <code>&#39;hello&#39;</code>中搜索匹配 <code>&#39;l&#39;</code>只有 <code>&#39;l&#39;</code>被返回来。使用 <code>regexp</code>参数也是得到一样的结果。</p>
            <p>我们把字符 <code>&#39;l&#39;</code>更换为表达式 <code>/l/</code>:</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">let</span> string = <span class="string">&#x27;Hello&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> matches = string.match(<span class="regexp">/l/</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(matches[<span class="number">0</span>]) <span class="comment">// &#x27;l&#x27;</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h3 id="添加-g"><a href="#添加-g" class="headerlink" title="添加 /g"></a>添加 /g</h3>
            <p><code>String.match</code>使用正则表达式带上 <code>/g</code>标签会返回多个匹配。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">let</span> string = <span class="string">&#x27;Hello&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> ret = string.match(<span class="regexp">/l/g</span>) <span class="comment">// [&#x27;l&#x27;, &#x27;l&#x27;]</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>Great…在低于 <code>ES10</code>的环境中我们得到了多个匹配结果，并且一直有效。</p>
            <p>那么为什么要用全新的 <code>matchAll</code>方法呢？在我们更详细地回答这个问题之前，让我们来看看 <code>capture group</code>。如果不出意外，你可能会学到新的有关正则表达式的东西。</p>
            <h3 id="正则表达式捕获组"><a href="#正则表达式捕获组" class="headerlink" title="正则表达式捕获组"></a>正则表达式捕获组</h3>
            <p>在正则表达式中捕获组只是在 <code>()</code>括号中提取匹配。你可以从 <code>/regex/.exec(string)</code>和 <code>string.match</code>捕获组。</p>
            <p>通常捕获组是在匹配规则中被创建的。输出对象上创建 <code>groups</code>属性如： <code>(?&lt;name&gt;)</code>。要创建一个新的组名，只需在括号内添加 <code>(?&lt;name&gt;)</code>属性，分组（模式）匹配将成为附加到 <code>match</code>对象的 <code>groups.name</code>。</p>
            <p><strong>看一个实际的例子</strong></p>
            <p>字符串标本匹配</p>
            <p><img src="" data-original="/images/es/0002.png" alt="0002"></p>
            <p>创建<code>match.groups.color &amp; match.groups.bird</code>匹配：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> string = <span class="string">&#x27;black*raven lime*parrot white*seagull&#x27;</span></span><br><span class="line"><span class="keyword">const</span> regex = <span class="regexp">/(?&lt;color&gt;.*?)\*(?&lt;bird&gt;[a-z0-9]+)/g</span></span><br><span class="line"><span class="keyword">while</span> (match = regex.exec(string) &#123;</span><br><span class="line">  <span class="keyword">let</span> value = match[<span class="number">0</span>]</span><br><span class="line">  <span class="keyword">let</span> index = match.index</span><br><span class="line">  <span class="keyword">let</span> input = match.input</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;value&#125;</span> at <span class="subst">$&#123;index&#125;</span> with &#x27;<span class="subst">$&#123;input&#125;</span>&#x27;`</span>)</span><br><span class="line">  <span class="built_in">console</span>.log(match.groups.color)</span><br><span class="line">  <span class="built_in">console</span>.log(match.groups.bird)</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>需要多次调用<code>regex.exec</code>方法来遍历整个搜索结果。在每次迭代调用<code>.exec</code>时，会显示下一个结果（它不会立即返回所有匹配项）。</p>
            <p>控制台输出：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">black*raven at <span class="number">0</span> <span class="keyword">with</span> <span class="string">&#x27;black*raven lime*parrot white*seagull&#x27;</span></span><br><span class="line">black</span><br><span class="line">raven</span><br><span class="line">lime*parrot at <span class="number">11</span> <span class="keyword">with</span> <span class="string">&#x27;black*raven lime*parrot white*seagull&#x27;</span></span><br><span class="line">lime</span><br><span class="line">parrot</span><br><span class="line">white*seagull at <span class="number">23</span> <span class="keyword">with</span> <span class="string">&#x27;black*raven lime*parrot white*seagull&#x27;</span></span><br><span class="line">white</span><br><span class="line">seagull</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>这里有一个怪事：</p>
            <blockquote>
              <p>如果你从这个正则表达式中删除/ g，你将永远在第一个结果上创建一个无限循环循环。这在过去是一个巨大的痛苦。想象一下从某个数据库接收正则表达式，你不确定它是否在最后有/ g。你必须先检查它，等等。</p>
            </blockquote>
            <p>现在我们有足够的背景知识回答这个问题：</p>
            <h3 id="最好使用-matchAll"><a href="#最好使用-matchAll" class="headerlink" title="最好使用 .matchAll()"></a>最好使用 .matchAll()</h3>
            <ol>
              <li>使用捕获组时更加优雅。捕获组知识带有提取模式（）的正则表达式的一部分。</li>
              <li>它返回一个<strong>迭代器</strong>而不是数组，迭代器本身很有用。</li>
              <li>可以使用<strong>扩展运算符…将迭代器</strong>转为<strong>数组</strong>。</li>
              <li>它避免使用带<code>/g</code>标志的**正则表达式…**当从数据库或外部源检索未知的正则表达式并与古老的RegEx对象一起使用时非常有用。</li>
              <li>使用<code>RegExp</code>对象创建的正则表达式不能使用点（<code>.</code>）运算符链接。</li>
              <li><strong>高级：RegEx</strong>对象跟踪最后匹配位置的内部<code>.lastIndex</code>属性，这可能对复杂案例有破坏性的事情。</li>
            </ol>
            <h3 id="matchAll-如何工作"><a href="#matchAll-如何工作" class="headerlink" title=".matchAll()如何工作"></a>.matchAll()如何工作</h3>
            <p>这是一简单个例子。</p>
            <p>我们尝试匹配字符串<code>Hello</code>的所有<code>e</code>和<code>l</code>。因为返回了<code>iterator</code>,所以我们用<code>for ... of</code>处理它。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="comment">// Match all occurrences of the letters: &#x27;e&#x27; 或者 &#x27;l&#x27;</span></span><br><span class="line"><span class="keyword">let</span> iterator = <span class="string">&#x27;hello&#x27;</span>.matchAll(<span class="regexp">/[el]/</span>)</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">const</span> match <span class="keyword">of</span> iterator) &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(match)</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <p>如上，你可以跳过<code>/g</code>，<code>.matchAll</code>不需要它。结果：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">[ <span class="string">&#x27;e&#x27;</span>, <span class="attr">index</span>: <span class="number">1</span>, <span class="attr">input</span>: <span class="string">&#x27;hello&#x27;</span> ] <span class="comment">// Iteration 1</span></span><br><span class="line">[ <span class="string">&#x27;l&#x27;</span>, <span class="attr">index</span>: <span class="number">2</span>, <span class="attr">input</span>: <span class="string">&#x27;hello&#x27;</span> ] <span class="comment">// Iteration 2</span></span><br><span class="line">[ <span class="string">&#x27;l&#x27;</span>, <span class="attr">index</span>: <span class="number">3</span>, <span class="attr">input</span>: <span class="string">&#x27;hello&#x27;</span> ] <span class="comment">// Iteration 3</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <p>使用<code>.matchAll()</code>捕获组示例：<code>.matchAll()</code>具有上面列举的所有好处，它是一个<strong>迭代器</strong>，所以我们可以用它来循环，这就是整个<strong>句法</strong>差异。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> string = <span class="string">&#x27;black*raven lime*parrot white*seagull&#x27;</span>;</span><br><span class="line"><span class="keyword">const</span> regex = <span class="regexp">/(?&lt;color&gt;.*?)\*(?&lt;bird&gt;[a-z0-9]+)/</span>;</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">const</span> match <span class="keyword">of</span> string.matchAll(regex)) &#123;</span><br><span class="line">  <span class="keyword">let</span> value = match[<span class="number">0</span>];</span><br><span class="line">  <span class="keyword">let</span> index = match.index;</span><br><span class="line">  <span class="keyword">let</span> input = match.input;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;value&#125;</span> at <span class="subst">$&#123;index&#125;</span> with &#x27;<span class="subst">$&#123;input&#125;</span>&#x27;`</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(match.groups.color);</span><br><span class="line">  <span class="built_in">console</span>.log(match.groups.bird);</span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <p>注意去掉<code>/g</code>标志，因为<code>.matchAll()</code>已经隐含了它。<br>结果输出：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">black*raven at <span class="number">0</span> <span class="keyword">with</span> <span class="string">&#x27;black*raven lime*parrot white*seagull&#x27;</span></span><br><span class="line">black</span><br><span class="line">raven</span><br><span class="line">lime*parrot at <span class="number">11</span> <span class="keyword">with</span> <span class="string">&#x27;black*raven lime*parrot white*seagull&#x27;</span></span><br><span class="line">lime</span><br><span class="line">parrot</span><br><span class="line">white*seagull at <span class="number">23</span> <span class="keyword">with</span> <span class="string">&#x27;black*raven lime*parrot white*seagull&#x27;</span></span><br><span class="line">white</span><br><span class="line">seagull</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <p>也许在美学上它与循环实现时的原始<code>regex.exec</code>非常相似。但如前所述，由于上述许多原因，这是更好的方法。并且删除<code>/g</code>不会导致无限循环。</p>
            <h2 id="动态-import"><a href="#动态-import" class="headerlink" title="动态 import"></a>动态 import</h2>
            <p>ES Module 是一套静态的模块系统：</p>
            <ul>
              <li>静态加载：<code>import/export</code>声明只能出现在顶层作用域，<strong>不支持按需加载、懒加载</strong></li>
              <li>静态标识：模块标识只能是字符串字面量，<strong>不支持运行时动态计算而来的模块名</strong></li>
            </ul>
            <p>因此有一些不可避免的问题：</p>
            <ul>
              <li>影响首屏性能：</li>
              <li>难以提前确定目标模块标识的场景：比如微信、支付宝公众号h5</li>
              <li>特定情况下加载指定模块</li>
            </ul>
            <p>为了满足这些需要动态加载模块的场景，ES2020 推出了动态 import 特性（<code>import()</code>）</p>
            <p>现在可以将导入分配给一个变量：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">element.addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">    <span class="keyword">const</span> <span class="built_in">module</span> = <span class="keyword">await</span> <span class="keyword">import</span>(<span class="string">&#x27;./api-scripts/button-click.js&#x27;</span>)</span><br><span class="line">    <span class="built_in">module</span>.clickEvent()</span><br><span class="line">&#125;)</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>相对<code>import</code>声明，<code>import()</code>有如下特点：</p>
            <ul>
              <li>能够在函数、分支等非顶层作用域使用，按需加载、懒加载都不是问题</li>
              <li>模块标识支持变量传入，可动态计算确定模块标识</li>
              <li>不仅限于module，在普通的script中也能使用</li>
            </ul>
            <h2 id="BigInt-任意精度整数"><a href="#BigInt-任意精度整数" class="headerlink" title="BigInt - 任意精度整数"></a>BigInt - 任意精度整数</h2>
            <p><code>BigInt</code>是第7种原始类型。</p>
            <p><code>BigInt</code>是一个任意精度的整数。这意味着变量现在可以代表2^53个数字。而且最大限度是9007199254740992。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> b = <span class="number">1n</span>; <span class="comment">//追加n来创建一个BigInt</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>在过去的整数值大于9007199254740992不支持。如果超出，则该值将锁定为 <code>MAX_SAFE_INTEGER + 1</code>：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> limit = <span class="built_in">Number</span>.MAX_SAFE_INTEGER;</span><br><span class="line"><span class="comment">// 9007199254740991</span></span><br><span class="line"></span><br><span class="line">limit + <span class="number">1</span>;</span><br><span class="line"><span class="comment">// 9007199254740992</span></span><br><span class="line"></span><br><span class="line">limit + <span class="number">2</span>;</span><br><span class="line"><span class="comment">// 9007199254740992 &lt;--- MAX_SAFE_INTEGER + 1 exceeded</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> larger = <span class="number">9007199254740991n</span>;</span><br><span class="line"><span class="comment">// 9007199254740991n</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> integer = BigInt(<span class="number">9007199254740991</span>);</span><br><span class="line"><span class="comment">// 9007199254740991n</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> same = BigInt(<span class="string">&quot;9007199254740991&quot;</span>);</span><br><span class="line"><span class="comment">// 9007199254740991n</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p><strong>typeof</strong></p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">typeof</span> <span class="number">10</span>;</span><br><span class="line"><span class="comment">// &#x27;number&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">typeof</span> <span class="number">10n</span>;</span><br><span class="line"><span class="comment">// &#x27;bigint&#x27;</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p><strong>=== ==</strong></p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="number">10n</span> === BigInt(<span class="number">10</span>);</span><br><span class="line"><span class="comment">// true</span></span><br><span class="line"></span><br><span class="line"><span class="number">10n</span> == <span class="number">10</span>;</span><br><span class="line"><span class="comment">// true</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>*** /**</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="number">200n</span> / <span class="number">10n</span></span><br><span class="line"><span class="comment">// 20n</span></span><br><span class="line"></span><br><span class="line"><span class="number">200n</span> / <span class="number">20</span></span><br><span class="line"><span class="comment">// Uncaught TypeError: </span></span><br><span class="line"><span class="comment">// Cannot mix BigInt and other types, use explicit conversions</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p><strong>- +</strong></p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">-<span class="number">100n</span></span><br><span class="line"><span class="comment">// -100n</span></span><br><span class="line"></span><br><span class="line">+<span class="number">100n</span></span><br><span class="line"><span class="comment">// Uncaught TypeError:</span></span><br><span class="line"><span class="comment">// Cannot convert a BigInt value to a number</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h2 id="export-与-import-的复合写法补充"><a href="#export-与-import-的复合写法补充" class="headerlink" title="export 与 import 的复合写法补充"></a>export 与 import 的复合写法补充</h2>
            <p>es2020之前写法</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">import</span> * <span class="keyword">as</span> ns <span class="keyword">from</span> <span class="string">&quot;mod&quot;</span>;</span><br><span class="line"><span class="keyword">export</span> &#123;ns&#125;;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>es2020之后写法</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">export</span> * <span class="keyword">as</span> ns <span class="keyword">from</span> <span class="string">&quot;mod&quot;</span>;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h2 id="返回模块的元信息-import-meta"><a href="#返回模块的元信息-import-meta" class="headerlink" title="返回模块的元信息 import.meta"></a>返回模块的元信息 import.meta</h2>
            <p><code>import.meta</code>是一个给JavaScript模块暴露特定上下文的元数据属性的对象。它包含了这个模块的信息，比如说这个模块的URL。</p>
            <p>这里有一个 <code>my-module.mjs</code>模块</p>
            <figure class="highlight html">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;module&quot;</span> <span class="attr">src</span>=<span class="string">&quot;my-module.mjs&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <p>你可以通过 <code>import.meta</code> 对象获取这个模块的元数据信息.</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="built_in">console</span>.log(<span class="keyword">import</span>.meta); <span class="comment">// &#123; url: &quot;file:///home/user/my-module.mjs&quot; &#125;</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>它返回一个带有url属性的对象，指明模块的基本URL。也可以是外部脚本的URL，还可以是内联脚本所属文档的URL。</p>
            <p>注意，url也可能包含参数或者哈希（比如后缀?或#）</p>
            <p>在脚本中引入别的脚本同样生效：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="comment">// index.mjs</span></span><br><span class="line"><span class="keyword">import</span> <span class="string">&#x27;./index2.mjs?someURLInfo=5&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// index2.mjs</span></span><br><span class="line"><span class="keyword">new</span> URL(<span class="keyword">import</span>.meta.url).searchParams.get(<span class="string">&#x27;someURLInfo&#x27;</span>); <span class="comment">// 5</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h2 id="规范for-in循环的某些行为"><a href="#规范for-in循环的某些行为" class="headerlink" title="规范for-in循环的某些行为"></a>规范for-in循环的某些行为</h2>
            <p>ES2020 不要求统一属性遍历顺序，而是对遍历过程中的一些特殊 Case 明确定义了一些规则：</p>
            <ul>
              <li>遍历不到 Symbol 类型的属性</li>
              <li>遍历过程中，目标对象的属性能被删除，忽略掉尚未遍历到却已经被删掉的属性</li>
              <li>遍历过程中，如果有新增属性，不保证新的属性能被当次遍历处理到</li>
              <li>属性名不会重复出现（一个属性名最多出现一次）</li>
              <li>目标对象整条原型链上的属性都能遍历到</li>
            </ul>
            <h2 id="空值合并运算符"><a href="#空值合并运算符" class="headerlink" title="空值合并运算符 ??"></a>空值合并运算符 ??</h2>
            <p><strong>空值合并运算符（<code>??</code>）</strong>是一个逻辑运算符，当左侧的操作数为 <code>null</code> 或者 <code>undefined</code> 时，返回其右侧操作数，否则返回左侧操作数。</p>
            <p>与逻辑或运算符（<code>||</code>）不同，逻辑或运算符会在左侧操作数为假值时返回右侧操作数。也就是说，如果使用 <code>||</code> 来为某些变量设置默认值，可能会遇到意料之外的行为。比如为假值（例如，<code>&#39;&#39;</code> 或 <code>0</code>）时。见下面的例子。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">actualValue ?? defaultValue   <span class="comment">// 当 actualValue 为空字符串或者数字0的时候返回actualValue</span></span><br><span class="line"><span class="comment">// 等价于</span></span><br><span class="line">actualValue !== <span class="literal">undefined</span> &amp;&amp; actualValue !== <span class="literal">null</span> ? actualValue : defaultValue</span><br><span class="line"><span class="comment">// 逻辑或运算符</span></span><br><span class="line">actualValue || defaultValue   <span class="comment">// 当 actualValue 为空字符串或者数字0的时候返回defaultValue</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>


            <h2 id="可选链操作符"><a href="#可选链操作符" class="headerlink" title="可选链操作符"></a>可选链操作符</h2>
            <p>在 ES2020 之前，如果要访问 JavaScript 中对象的嵌套属性，则必须在每个级别检查是否为 null 或 undefined，否则最终将会抛出 TypeError。</p>
            <p>为了避免出现 TypeError，我们将不得不创建临时变量或执行一系列增量 &amp;&amp; 调用，这看起来很丑陋，并且同时占用了空间和时间。</p>
            <p>例如：</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">const obj &#x3D; &#123;</span><br><span class="line">  prop: &#123;</span><br><span class="line">    a: &quot;value&quot;</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; before ES2020 - no checks</span><br><span class="line">obj.foo.a  &#x2F;&#x2F; TypeError: Cannot read property &#39;a&#39; of undefined</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; before ES2020 - incremental nested checks</span><br><span class="line">obj.foo &amp;&amp; obj.foo.b   &#x2F;&#x2F; undefined</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>在ES2020中，通过可选链操作符 ?. ，现在我们就可以内联进行这些检查了。</p>
            <h3 id="描述"><a href="#描述" class="headerlink" title="描述"></a>描述</h3>
            <p>可选链操作符( <code>?.</code> )允许读取位于连接对象链深处的属性的值，而不必明确验证链中的每个引用是否有效。<code>?.</code> 操作符的功能类似于 <code>.</code> 链式操作符，不同之处在于，在引用为空(<code>nullish</code> ) (<code>null</code> 或者 <code>undefined</code>) 的情况下不会引起错误，该表达式短路返回值是 <code>undefined</code>。与函数调用一起使用时，如果给定的函数不存在，则返回 <code>undefined</code>。</p>
            <p>上面的写法就可以像下面一样：</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">obj?.foo?.a</span><br><span class="line"></span><br><span class="line">obj?.foo?.b</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h3 id="可选链与函数调用"><a href="#可选链与函数调用" class="headerlink" title="可选链与函数调用"></a>可选链与函数调用</h3>
            <p>函数调用时如果被调用的方法不存在，使用可选链可以使表达式自动返回<code>undefined</code>而不是抛出一个异常。</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">let result &#x3D; someInterface?.customMethod?.()</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>如果存在一个属性名且不是函数, 使用 <code>?.</code> 仍然会产生一个 <code>TypeError</code> 异常 (<code>x.y is not a function</code>).</p>
            <h3 id="可选链访问数组元素"><a href="#可选链访问数组元素" class="headerlink" title="可选链访问数组元素"></a>可选链访问数组元素</h3>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">let arrayItem &#x3D; arr?.[42]</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h3 id="特性"><a href="#特性" class="headerlink" title="特性"></a>特性</h3>
            <ul>
              <li>可选链不能用于赋值</li>
              <li>短路计算<br><code>potentiallyNullObj?.[x++]</code>，当前面是<code>null</code>或者<code>undefined</code>时，后面的<code>x</code>不进行自加</li>
              <li>连用可选链操作符</li>
              <li>与空值合并运算符一起使用<br><code>customer?.city ?? &quot;暗之城&quot;</code></li>
            </ul>
            <h3 id="Babel插件转换"><a href="#Babel插件转换" class="headerlink" title="Babel插件转换"></a>Babel插件转换</h3>
            <p><a target="_blank" rel="noopener" href="https://babeljs.io/docs/en/babel-plugin-syntax-optional-chaining">https://babeljs.io/docs/en/babel-plugin-syntax-optional-chaining</a></p>
            <h2 id="Promise-allSettled"><a href="#Promise-allSettled" class="headerlink" title="Promise.allSettled"></a>Promise.allSettled</h2>
            <p><code>Promise.allSettled()</code>方法接受一组 Promise 实例作为参数，包装成一个新的 Promise 实例。只有等到所有这些参数实例都返回结果，不管是<code>fulfilled</code>还是<code>rejected</code>，包装实例才会结束。</p>
            <p>该方法返回的新的 Promise 实例，一旦结束，状态总是<code>fulfilled</code>，不会变成<code>rejected</code>。状态变成<code>fulfilled</code>后，Promise 的监听函数接收到的参数是一个数组，每个成员对应一个传入<code>Promise.allSettled()</code>的 Promise 实例。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">const</span> resolved = <span class="built_in">Promise</span>.resolve(<span class="number">42</span>);</span><br><span class="line"><span class="keyword">const</span> rejected = <span class="built_in">Promise</span>.reject(-<span class="number">1</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> allSettledPromise = <span class="built_in">Promise</span>.allSettled([resolved, rejected]);</span><br><span class="line"></span><br><span class="line">allSettledPromise.then(<span class="function"><span class="keyword">function</span> (<span class="params">results</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(results);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// [</span></span><br><span class="line"><span class="comment">//    &#123; status: &#x27;fulfilled&#x27;, value: 42 &#125;,</span></span><br><span class="line"><span class="comment">//    &#123; status: &#x27;rejected&#x27;, reason: -1 &#125;</span></span><br><span class="line"><span class="comment">// ]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 过滤出成功的请求</span></span><br><span class="line"><span class="keyword">const</span> successfulPromises = allSettledPromise.filter(<span class="function"><span class="params">p</span> =&gt;</span> p.status === <span class="string">&#x27;fulfilled&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 过滤出失败的请求</span></span><br><span class="line"><span class="keyword">const</span> successfulPromises = allSettledPromise.filter(<span class="function"><span class="params">p</span> =&gt;</span> p.status === <span class="string">&#x27;rejected&#x27;</span>);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>对于只关心操作有没有结束，<code>Promise.assSettled</code>方法很有用。</p>
            <h2 id="标准化的-globalThis-对象"><a href="#标准化的-globalThis-对象" class="headerlink" title="标准化的 globalThis 对象"></a>标准化的 globalThis 对象</h2>
            <p>ES10之前全局<code>this</code>没有标准化。</p>
            <p>不同环境中获取全局对象的方法不同</p>
            <ul>
              <li>浏览器里面，顶层对象是window，但 Node 和 Web Worker 没有window。</li>
              <li>浏览器和 Web Worker 里面，self也指向顶层对象，但是 Node 没有self。</li>
              <li>Node 里面，顶层对象是global，但其他环境都不支持</li>
            </ul>
            <p>生产代码中，你必须手动添加如下代码来标准化多个平台的全局对象。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="comment">// 方法一</span></span><br><span class="line">(<span class="keyword">typeof</span> <span class="built_in">window</span> !== <span class="string">&#x27;undefined&#x27;</span></span><br><span class="line">   ? <span class="built_in">window</span></span><br><span class="line">   : (<span class="keyword">typeof</span> process === <span class="string">&#x27;object&#x27;</span> &amp;&amp;</span><br><span class="line">      <span class="keyword">typeof</span> <span class="built_in">require</span> === <span class="string">&#x27;function&#x27;</span> &amp;&amp;</span><br><span class="line">      <span class="keyword">typeof</span> <span class="built_in">global</span> === <span class="string">&#x27;object&#x27;</span>)</span><br><span class="line">     ? <span class="built_in">global</span></span><br><span class="line">     : <span class="built_in">this</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法二</span></span><br><span class="line"><span class="keyword">var</span> getGlobal = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> self !== <span class="string">&#x27;undefined&#x27;</span>) &#123; <span class="keyword">return</span> self; &#125;</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> <span class="built_in">window</span> !== <span class="string">&#x27;undefined&#x27;</span>) &#123; <span class="keyword">return</span> <span class="built_in">window</span>; &#125;</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> <span class="built_in">global</span> !== <span class="string">&#x27;undefined&#x27;</span>) &#123; <span class="keyword">return</span> <span class="built_in">global</span>; &#125;</span><br><span class="line">  <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;unable to locate global object&#x27;</span>);</span><br><span class="line">&#125;;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>但即使这样也并不总是奏效。所以<code>ES11</code>添加了<code>globalThis</code>对象，从现在开始应该在任何平台上访问全局作用域：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="comment">// Access global array constructor</span></span><br><span class="line">globalThis.Array(<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>);</span><br><span class="line">⇨ [<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment">// Similar to window.v = &#123; flag: true &#125; in &lt;= ES5</span></span><br><span class="line">globalThis.v = &#123; <span class="attr">flag</span>: <span class="literal">true</span> &#125;;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(globalThis.v);</span><br><span class="line">⇨ &#123; <span class="attr">flag</span>: <span class="literal">true</span> &#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>


            <h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1>
            <p><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/152245696?from_voters_page=true">ES11来了，还学得动吗？</a><br><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/3e59df36342a">解读ES2020（ES11）新特性</a><br><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/144195905">JavaScript 中的可选链操作符</a><br><a target="_blank" rel="noopener" href="https://es6.ruanyifeng.com/?search=globalThis&x=0&y=0#docs/let#globalThis-%E5%AF%B9%E8%B1%A1">globalThis 对象</a></p>
            <p><a target="_blank" rel="noopener" href="https://es6.ruanyifeng.com/?search=import&x=0&y=0#docs/module#export-%E4%B8%8E-import-%E7%9A%84%E5%A4%8D%E5%90%88%E5%86%99%E6%B3%95">export 与 import 的复合写法</a><br><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator">空值合并运算符 MDN</a><br><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Optional_chaining">可选链操作符 MDN</a><br><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/import.meta">import.meta</a></p>

          </div>





          <footer class="post-footer">
            <div class="post-tags">
              <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
              <a href="/tags/Ecma/" rel="tag"># Ecma</a>
              <a href="/tags/ECMAScript/" rel="tag"># ECMAScript</a>
              <a href="/tags/ES11/" rel="tag"># ES11</a>
              <a href="/tags/ES2020/" rel="tag"># ES2020</a>
              <a href="/tags/ECMAScript-2020/" rel="tag"># ECMAScript 2020</a>
            </div>



            <div class="post-nav">
              <div class="post-nav-item">
                <a href="/blob/2021-05-31-automatic-upload-of-small-program-code-command-line/" rel="prev" title="小程序代码命令行自动上传">
                  <i class="fa fa-chevron-left"></i> 小程序代码命令行自动上传
                </a>
              </div>
              <div class="post-nav-item">
                <a href="/blob/2021-06-08-new-features-of-javsscript-es12-&-es2021/" rel="next" title="JavsScript ES12&ES2021的新特性">
                  JavsScript ES12&ES2021的新特性 <i class="fa fa-chevron-right"></i>
                </a>
              </div>
            </div>
          </footer>
        </article>
      </div>







      <script>
        window.addEventListener('tabs:register', () => {
          let {
            activeClass
          } = CONFIG.comments;
          if (CONFIG.comments.storage) {
            activeClass = localStorage.getItem('comments_active') || activeClass;
          }
          if (activeClass) {
            const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
            if (activeTab) {
              activeTab.click();
            }
          }
        });
        if (CONFIG.comments.storage) {
          window.addEventListener('tabs:click', event => {
            if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
            const commentClass = event.target.classList[1];
            localStorage.setItem('comments_active', commentClass);
          });
        }
      </script>
    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


      <div class="copyright">
        &copy;
        <span itemprop="copyrightYear">2021</span>
        <span class="with-love">
          <i class="fa fa-heart"></i>
        </span>
        <span class="author" itemprop="copyrightHolder">holidaypenguin</span>
      </div>
      <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
      </div>

    </div>
  </footer>


  <script size="300" alpha="0.1" zIndex="-1" src="https://cdn.jsdelivr.net/npm/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
  <script src="/js/love.js"></script>

  <script src="/js/development.js"></script>
  <script src="/js/utils.js"></script>
  <script src="/js/motion.js"></script>
  <script src="/js/schemes/muse.js"></script>
  <script src="/js/next-boot.js"></script>


  <script src="/js/local-search.js"></script>









  <script>
    (function() {
      function leancloudSelector(url) {
        url = encodeURI(url);
        return document.getElementById(url).querySelector('.leancloud-visitors-count');
      }

      function addCount(Counter) {
        const visitors = document.querySelector('.leancloud_visitors');
        const url = decodeURI(visitors.id);
        const title = visitors.dataset.flagTitle;

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            if (results.length > 0) {
              const counter = results[0];
              leancloudSelector(url).innerText = counter.time + 1;
              Counter('put', '/classes/Counter/' + counter.objectId, {
                  time: {
                    '__op': 'Increment',
                    'amount': 1
                  }
                })
                .catch(error => {
                  console.error('Failed to save visitor count', error);
                });
            } else {
              Counter('post', '/classes/Counter', {
                  title,
                  url,
                  time: 1
                })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      function showTime(Counter) {
        const visitors = document.querySelectorAll('.leancloud_visitors');
        const entries = [...visitors].map(element => {
          return decodeURI(element.id);
        });

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url: {
              '$in': entries
            }
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            for (let url of entries) {
              const target = results.find(item => item.url === url);
              leancloudSelector(url).innerText = target ? target.time : 0;
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      const {
        app_id,
        app_key,
        server_url
      } = {
        "enable": true,
        "app_id": "povuqNsSqFodlakVIwtEX5kb-gzGzoHsz",
        "app_key": "zXD40RDtDB3DMtpC89k0AK7g",
        "server_url": null,
        "security": false
      };

      function fetchData(api_server) {
        const Counter = (method, url, data) => {
          return fetch(`${api_server}/1.1${url}`, {
            method,
            headers: {
              'X-LC-Id': app_id,
              'X-LC-Key': app_key,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
          });
        };
        if (CONFIG.page.isPost) {
          if (CONFIG.hostname !== location.hostname) return;
          addCount(Counter);
        } else if (document.querySelectorAll('.post-title-link').length >= 1) {
          showTime(Counter);
        }
      }

      const api_server = app_id.slice(-9) === '-MdYXbMMI' ? `https://${app_id.slice(0, 8).toLowerCase()}.api.lncldglobal.com` : server_url;

      if (api_server) {
        fetchData(api_server);
      } else {
        fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
          .then(response => response.json())
          .then(({
            api_server
          }) => {
            fetchData('https://' + api_server);
          });
      }
    })();
  </script>



<script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(n){n.imageLazyLoadSetting.processImages=o;var e=n.imageLazyLoadSetting.isSPA,i=n.imageLazyLoadSetting.preloadRatio||1,r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]"));function o(){e&&(r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")));for(var t,a=0;a<r.length;a++)0<=(t=(t=r[a]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(n.innerHeight*i||document.documentElement.clientHeight*i)&&function(){var t,e,n,i,o=r[a];t=o,e=function(){r=r.filter(function(t){return o!==t})},n=new Image,i=t.getAttribute("data-original"),n.onload=function(){t.src=i,e&&e()},t.src!==i&&(n.src=i)}()}o(),n.addEventListener("scroll",function(){var t,e;t=o,e=n,clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(e)},500)})}(this);</script></body>

</html>